const { form } = layui

async function getSelect() {
  const res = await GetArticleList()
  console.log(res)
  res.data.data.forEach(function (item) {
    $('select[name=cate_id]').append(
      `<option value=${item.Id} lay-verify="cate">${item.name}</option>`
    )
    form.render('select', 'edit')
  })
}
getSelect()
//初始化富文本编辑器
initEditor()
//初始化裁剪插件
let cropper = new Cropper($('#image')[0], {
  aspectRatio: 1, // 裁剪图层的横纵比例
  preview: $('.img-preview'), // 多看文档里每个属性的意思, 一般都会有, 实在没用自己写/换个插件
})
$('.layui-form').on('submit', function (e) {
  e.preventDefault()
  form.verify({
    articleTitle: [
      /^[\u4E00-\u9FA5a-zA-Z0-9_-]+$/,
      '标题只能是中英文, 数字下划线中划线组成',
    ],
    // 分类判断
    cate: function () {
      return $('select[name=cate_id]').val().length == 0 && '请选择分类'
    },
  })
  let htmlStr = tinyMCE.activeEditor.getContent()
  const fm = new FormData($('.layui-form')[0])
  fm.set('content', htmlStr)
  fm.forEach(function (value, key) {
    console.log(value, key)
  })
  console.log(fm)
  let canvas = cropper.getCroppedCanvas({
    width: 100,
    height: 100,
  })
  canvas.toBlob(async function (blobObj) {
    console.log(blobObj)
    fm.append('cover_img', blobObj)
    const res = await PostNewArticle(fm)
    console.log(res)
    location.href = '../list/list.html'
  })
})
$('#select').on('click', function () {
  let cropper = new Cropper($('#image')[0], {
    aspectRatio: 1, // 裁剪图层的横纵比例
    preview: $('.img-preview'), // 多看文档里每个属性的意思, 一般都会有, 实在没用自己写/换个插件
  })
  $('.select').on('click', function () {
    console.log('---')
    $('#file').click()
  })
  $('#file').on('change', function (e) {
    console.log(e.target.files[0])
    const file = e.target.files[0]
    const str = URL.createObjectURL(file)
    cropper.replace(str)
    getPic()
  })
  $('.sure').on('click', async function () {
    let canvas = cropper.getCroppedCanvas({
      width: 100,
      height: 100,
    })
    let base64Str = canvas.toDataURL('image/jpeg')
    base64Str = encodeURIComponent(base64Str)
    const res = await PostUploadAvatar({ avatar: base64Str })
    console.log(res)
    window.parent.reqGetInfo()
  })
  async function getPic() {
    const res = await GetUserInfo()
    console.log(res)
    const userpic = res.data.data.user_pic
    console.log(userpic)
    if (userpic) {
      $('#image').attr('src', userpic)
    }
  }
  getPic()
})
